import {observable, computed, action, configure, runInAction} from 'mobx';
configure({enforceActions: 'observed'});
class AppleStore {
  @observable apples = [
    {
        id: 0,
        weight: 233,
        isEaten: false
    },
    {
        id: 1,
        weight: 235,
        isEaten: true
    },
    {
        id: 2,
        weight: 256,
        isEaten: false
    }
  ]
  @observable newAppleId = 3;
  @observable notEatenQuantity = 0;
  @observable notEatenWeight = 0;
  @observable EatenQuantity = 0;
  @observable EatenWeight = 0;
  @observable isPicking = false;
  @observable buttonText = '摘苹果';

  @computed
  get status() {
    let status = {
      appleNow: {
        quantity: 0,
        weight: 0
      },
      appleEaten: {
        quantity: 0,
        weight: 0
      }
    };
    this.apples.forEach(apple => {
      let selected = !apple.isEaten ? 'appleNow' : 'appleEaten';
      status[selected].quantity++;
      status[selected].weight += apple.weight;
    });
    return status;
  }

  @action.bound pickApple () {
    if (this.isPicking) {
        return;
    }
    this.isPicking = true;
    this.buttonText = '正在采摘...';
    setTimeout(() => {
      runInAction(() => {
        let weight = Math.floor(200 + Math.random() * 50);
        this.isPicking = false;
        this.buttonText = '摘苹果';
        this.apples.push({
            id: this.newAppleId++,
            weight: weight,
            isEaten: false
        });
      })
    }, 1000)
  }

  @action.bound eatApple (appleId) {
    this.apples.forEach((apple, index) => {
      if (apple.id === appleId) {
        this.apples[index].isEaten = true;
      }
    });
  }
}
const store = new AppleStore();
export default store